//
//  RecommendViewController.m
//  B
//
//  Created by 王展 on 15/11/5.
//  Copyright © 2015年 wangzhan. All rights reserved.
//

#import "RecommendViewController.h"
#import "ZNTCollectionViewCell.h"
#import "Model1.h"
#import "Model2.h"
#import "ListSecondTableViewCell.h"
#import "StoryViewController.h"
#import "BannerViewController.h"
#import "StotyDetainsViewController.h"
#import "TravelViewController.h"
@interface RecommendViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,SDCycleScrollViewDelegate>

@property (nonatomic ,strong)UICollectionView* collectView;
@property (nonatomic ,strong)UICollectionViewFlowLayout *flowLayout;
@property (nonatomic ,strong)NSMutableArray *allDataArray;
@property (nonatomic ,strong)NSMutableArray *allStoryArray;
@property (nonatomic ,strong)NSString *next_start;

@property (nonatomic ,strong)NSMutableArray *allBanner;

@property (nonatomic ,strong)UICollectionReusableView *myHeardView ;
@property (nonatomic ,strong)UILabel *labelOne;
@property (nonatomic ,strong)UILabel *labelTwo;
@property (nonatomic ,strong)UIButton *button;

@property (nonatomic ,assign)BOOL isUp;


@end

@implementation RecommendViewController

- (void) viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    for (UIView *view in self.tabBarController.view.subviews) {
        if ([view isKindOfClass:[BaseView class]]) {
            view.hidden = NO;
        }
    }
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.isUp = NO;
    [self setFlowLayout: [[UICollectionViewFlowLayout alloc]init]];
    [[self flowLayout] setSectionInset:UIEdgeInsetsMake(10 *XHIGHT, 15 *XWIDTH , 0, 15 *XWIDTH)];
    [[self flowLayout]  setMinimumLineSpacing:10];
    [[self flowLayout]  setMinimumInteritemSpacing:10];
    
    
    [self setCollectView:[[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, 375 *XWIDTH , (667*XHIGHT) - 64 - 49 ) collectionViewLayout:[self flowLayout] ]];
    [[self collectView]setBackgroundColor:[UIColor colorWithRed:251/255.0 green:247 /255.0 blue:236/255.0 alpha:1]];
    [[self collectView]setDelegate:self];
    [[self collectView]setDataSource:self];
    [[self view]addSubview:[self collectView]];
    
    [self setAllDataArray:[NSMutableArray array]];
    [[self collectView] registerClass:[ZNTCollectionViewCell class] forCellWithReuseIdentifier:@"cCell" ];
    [[self collectView] registerClass:[ListSecondTableViewCell class] forCellWithReuseIdentifier:@"sCell" ];
    [[self collectView] registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"heardView"];
    [[self collectView] registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"sHeardView"];
    
    [self creatHearderSubviews];
    
    
    [self herderRefrash];
    [self footerRefresh];
    [self setAllStoryArray:[NSMutableArray array]];
    [self setAllBanner:[NSMutableArray array]];
    [self setAllDataArray:[NSMutableArray array]];
    
    
    
    
}


- (void)herderRefrash {

    self.collectView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.isUp = NO;
        self.next_start = @"";
        [self getData:[self next_start]];
        
    }];
    [self.collectView.header beginRefreshing];
}

- (void)footerRefresh {

    self.collectView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        self.isUp = YES;
        NSLog(@"---------%@",self.next_start);
        [self getData:self.next_start];
        
    }];
    

}

- (void)creatHearderSubviews {
    
    self.button = [UIButton buttonWithType:UIButtonTypeCustom];
    self.button.frame = CGRectMake(330 *XWIDTH, 225 *XHIGHT, 40 *XWIDTH, 30 *XHIGHT);
    [self.button setTitle:@"更多" forState:UIControlStateNormal];
    self.button.titleLabel.font = [UIFont systemFontOfSize:15 *XWIDTH];
    [self.button addTarget:self action:@selector(buttonAction) forControlEvents:UIControlEventTouchUpInside];
    
    self.labelOne = [[UILabel alloc]initWithFrame:CGRectMake(20 *XWIDTH, 0, 200 *XWIDTH, 40 *XHIGHT)];
    
    self.labelTwo = [[UILabel alloc]initWithFrame:CGRectMake(20 *XWIDTH, 225 *XHIGHT, 200 *XWIDTH, 30 *XHIGHT)];
    
}


- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    
    if (kind == UICollectionElementKindSectionHeader ) {
        //代表是表头
        //heardView 是表头重用标识符
        //kind 代表区域类型是表头还是底部
        
        
        if ([indexPath section]== 1) {
            
            UICollectionReusableView *aView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"sHeardView" forIndexPath:indexPath];
            
            
            
            self.labelOne.text = @"精彩游记和专题";
            [aView addSubview:self.labelOne];
            
            return aView;
            
        } else {
            
            
            
            self.myHeardView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"heardView" forIndexPath:indexPath];
            
            [self.myHeardView addSubview:self.button];
            
            
            self.labelTwo.text = @"每日精选故事";
            [self.myHeardView addSubview:self.labelTwo];
            return self.myHeardView;
            
        }
        
        
        
    }
    return  nil;
}

- (void)buttonAction {
    
    StoryViewController *storyVC = [[StoryViewController alloc]init];
    
    [[self navigationController ] pushViewController:storyVC animated:YES];
    
    
}



- (void) getData:(NSString *)next_star {
    
    NSString *url_string = [NSString stringWithFormat:@"http://api.breadtrip.com/v5/index/%@",next_star];
    
    
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    [session GET:url_string parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        
        NSDictionary *dic = responseObject;
        if (self.isUp == NO) {
            [self setAllStoryArray:[NSMutableArray array]];
            [self setAllBanner:[NSMutableArray array]];
            [self setAllDataArray:[NSMutableArray array]];
        }
        
        self.next_start = [NSString stringWithFormat:@"?next_start=%@",[dic objectForKey:@"next_start"]];
        NSArray *array = [dic objectForKey:@"elements"];
        for (NSDictionary *dic in array) {
            
            Model1 *model = [[Model1 alloc]init];
            [model setValuesForKeysWithDictionary:dic];
            if (model.type == 1 ) {
                self.allBanner = [model data][0];
                NSLog(@"%@",self.allBanner);
                
            }
            
            if (model.type == 10) {
                
                NSDictionary *dict = [model data][0];
                NSDictionary *dicc = [dict objectForKey:@"user"];
                
                Model2 *mode2 = [[Model2 alloc]init];
                [mode2 setValuesForKeysWithDictionary:dict];
                mode2.autorName = [dicc objectForKey:@"name"];
                mode2.avatar_m = [dicc objectForKey:@"avatar_m"];
                [self.allStoryArray addObject:mode2];
                
            }
            
            if (model.type == 4) {
                
                NSDictionary *dict = [model data][0];
                NSDictionary *dicc = [dict objectForKey:@"user"];
                Model2 *mode2 = [[Model2 alloc]init];
                [mode2 setValuesForKeysWithDictionary:dict];
                mode2.autorName = [dicc objectForKey:@"name"];
                mode2.avatar_m = [dicc objectForKey:@"avatar_m"];
                [self.allDataArray addObject:mode2];
                
            }
            
            
            
            
        }
        
        [self createHeaderView];
        
        
        [self.collectView.header endRefreshing];
        [self.collectView.footer endRefreshing];
        [[self collectView]reloadData];
        
        NSLog(@"成功");
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        [self.collectView.header endRefreshing];
        [self.collectView.footer endRefreshing];
        NSLog(@"失败");
    }];
    
    
}


- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    
    if (section == 0 ) {
        
        CGSize size =    CGSizeMake(375 *XWIDTH, 260 *XHIGHT);
        return size;
    } else {
        
        CGSize size =    CGSizeMake(375 *XWIDTH, 30 *XHIGHT);
        return size;
        
    }
    
}


- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    if ([indexPath section] == 0 ) {
        
        CGSize size =    CGSizeMake(166 *XWIDTH, 180 *XHIGHT);
        
        return size;
    } else {
        
        CGSize size = CGSizeMake(360 *XWIDTH, 200 * XHIGHT);
        return size;
    }
    
}


-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    
    return 2;
    
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    if (section == 0) {
        
        
        
        return [[self allStoryArray] count];
    } else {
        
        return [[self allDataArray] count];
    }
}




- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0 ) {
        ZNTCollectionViewCell *cell =  [collectionView dequeueReusableCellWithReuseIdentifier:@"cCell" forIndexPath:indexPath];
        Model2 *mode = [self allStoryArray][indexPath.row];
        cell.model2 = mode;
        
        
        return cell;
        
    } else {
        
        //
        ListSecondTableViewCell *acell = [collectionView dequeueReusableCellWithReuseIdentifier:@"sCell" forIndexPath:indexPath];
        Model2 *model = self.allDataArray[indexPath.row];
        acell.model2 = model;
        return acell;
        
    }
    
    
    
    
    
    
    
}


-(void)createHeaderView
{
    NSMutableArray *array2 = [NSMutableArray array];
    
    for (NSDictionary *dic in [self allBanner]) {
        
        [array2 addObject:[dic objectForKey:@"image_url"]];
    }
    
    SDCycleScrollView *sdcycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, 375 *XWIDTH, 220 * XHIGHT) imageURLStringsGroup:nil];
    sdcycleScrollView.pageControlAliment = SDCycleScrollViewPageContolAlimentRight;
    sdcycleScrollView.delegate = self;
    self.collectView.showsHorizontalScrollIndicator = NO;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        sdcycleScrollView.imageURLStringsGroup = array2;
    });
    
    [self.myHeardView addSubview:sdcycleScrollView];
}


- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index {
    
    NSMutableArray * array = [NSMutableArray array];
    
    for (NSDictionary *dic in [self allBanner]) {
        [array addObject:[dic objectForKey:@"html_url"]];
    }
    
    BannerViewController * bannerVC = [[BannerViewController alloc]init];
    bannerVC.webUrl = array[index];
    [[self navigationController]pushViewController:bannerVC animated:YES];
    
}


- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    if ( [indexPath section] == 0) {
        
        Model2 *model  = [self allStoryArray][[indexPath row]];
        
        StotyDetainsViewController *storDVC = [[StotyDetainsViewController alloc]init];
        [storDVC setModel2:model];
        [[self navigationController] pushViewController:storDVC animated:NO];
        
        
    } else {
        
        TravelViewController * travelVC = [[TravelViewController alloc]init];
        Model2 *model  = [self.allDataArray objectAtIndex:indexPath.row];
        NSString *ID = [NSString stringWithFormat:@"%@",model.travelID];
        NSString *urlStr = [NSString stringWithFormat:@"http://api.breadtrip.com/trips/%@/waypoints/?gallery_mode=1&sign=dea21f7ed5e413c82c05a351135ed1e8",ID];
        travelVC.UrlStr = urlStr;
        travelVC.model2 = model;
        [self.navigationController pushViewController:travelVC animated:NO];
        
    }
    
    
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
